<template>
  <div class="addDiscussContainer responseContainer autoGrow flex-row">
    <div class="chooseAccount flex-column">
      <choose-service-account
        @serviceChange="serviceChange"
        :multiple="false"
      >
      <div class="autoGrow"></div>
        <div class="tips operateTip">
          <p>注：</p>
          <p>好友发送设置好的关键词后，可自动邀请对方进入群组</p>
          <p>可配合新好友应答功能实现，新增好友后自动应该，好友回复关键字后自动邀请进群</p>
        </div>
      </choose-service-account>
    </div>
    <div class="addDiscussMember flex-column">
      <div class="subTitle">关键词设置</div>
      <div class="keywordLabel">
        <span>回复关键字：</span>
      </div>
      <div>
        <input type="text" placeholder="请输入关键词" v-model="keyword" class="layui-input">
      </div>
    </div>
    <div class="discussDetailContainer autoGrow flex-column">
      <div class="flex-row chooseGroup">
        <div class="subTitle">选择群</div>
        <search placeholder="请输入关键字" @change="search=>this.search=search"></search>
      </div>
      <div class="groupList flex-row item">
        <label class="flex-row item" v-for="(group, i) in filteredGroups" :key="i">
          <input type="checkbox" @change="changeGroupSelect(group)" :checked="checkedGroups.includes(group.groupno)">
          <group
            :name="group.groupname"
            :avatar="group.avatar"
            :member="group.personnum"
            :friend="group.friendNum"
            class="group-item"
          />
        </label>
         
      </div>
      <div class="sendButtons">
        <button class="layui-btn layui-btn-sm" @click="confirmSend">确定</button>
      </div>
      <div class="subTitle">拉群记录</div>
      <div class="autoGrow flex-column detailList keywordGroups">
        <div class="ongoingItem flex-column"
          :key="index"
          v-for="(progress, index) in progressList">
          <div class="flex-row progressHead">
            <img :src="service.avatar" class="serviceAvatar" alt="">
            <div class="flex-column autoGrow servicesInfo">
              <div>{{service.nick}} &emsp; 关键词：{{progress.keyword}}</div>
              <div class="progressDetailInfo fontGrey">
                {{ formatTime(progress.createdate)}}
              </div>
            </div>
            <div class="rightButtons flex-column">
              <button class="layui-btn layui-btn-xs layui-btn-danger dismissGroup" @click="deleteSetting(progress)">删除</button>
              <button class="layui-btn layui-btn-xs layui-btn-warm" @click="toggleDetailShow(progress, index)">
                {{progress.showDetail ? '收起' : '详细'}}
              </button>
            </div>
          </div>
          <div class="progressTabs" v-if="progress.showDetail">
            <button
              @click="changeProgressListType('record', index)"
              :class="['layui-btn', 'layui-btn-xs', progress.listType!='record' && 'layui-btn-primary']">邀请记录</button>
            <button
              @click="changeProgressListType('set', index)"
              :class="['layui-btn', 'layui-btn-xs', progress.listType!='set' && 'layui-btn-primary']">设置群</button>
          </div>
          <div class="checkedUsers" v-if="progress.showDetail">
            <div class="progress-user" v-if="progress.listType=='record'">
              <div class="flex-row progress-user-item" v-for="(item, index) in progress.wxGroupKeywordItemList" :key="index">
                <friend
                  :name="item.nickname"
                  :avatar="item.avatar"
                  :wxid="item.wxid"
                  class="progress-friend-item"   
                />
                <group 
                  :name="groupMap[item.groupno].groupname"
                  :avatar="groupMap[item.groupno].avatar"
                  :member="groupMap[item.groupno].personnum"
                  :friend="groupMap[item.groupno].friendNum" 
                  class="progress-group-item"
                />
                <div class="flex-column progress-item-status">
                  <span>{{item.joinstatus===1?'对方已进群':'对方未进群'}}</span>
                  <span class="fontGrey" v-if="item.jointime">{{ formatTime(item.jointime) }}</span>
                </div>
              </div>
              <div v-if="!progress.wxGroupKeywordItemList || progress.wxGroupKeywordItemList.length==0">无记录</div>
            </div>
            <div class="progress-user" v-if="progress.listType=='set'">
              <div class="flex-row set-group-item" v-for="(groupno, index) in progress.groupnos.split(',')" :key="index">
                <group 
                    :name="groupMap[groupno].groupname"
                    :avatar="groupMap[groupno].avatar"
                    :member="groupMap[groupno].personnum"
                    :friend="groupMap[groupno].friendNum" 
                    class="progress-group-item"
                  />
                <button v-if="progress.groupnos.split(',').length>1" class="layui-btn layui-btn-xs layui-btn-danger dismissGroup set-group-del" @click="deleteSettngGroup(progress,groupno)">删除</button>  
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import ChooseServiceAccount from '@/components/chooseServiceAccount';
import UserListItem from '@/components/userListItem';
import QuickReplies from '@/components/quickReplies';
import Search from '@/components/search';
import Group from '@/components/group'
import Friend from '@/components/friend'

export default {
  name: 'keyword',
  data() {
    return {
      service: null,
      keyword: '',
      search: '',
      checkedGroups: [],
      groups: [],
      groupMap:{},
      progressList: [],
       
    }
  },
  mounted() {
    let friends = [];
    for(let i=0; i<30; i++) {
      for(let j=0; j<50; j++) {
        friends.push({
          wxid: Math.random().toString(16).slice(2),
          avatar: '',
          name: `用户${j}${i}`,
          status: i % 2 == 0 ? 'success' : 'fail',
          gender: 0,
          groupNickname: `小${j}${i}`,
          group: {
            wxid: Math.random().toString(16).slice(2),
            avatar: '',
            name: `群聊${i}`,
            memberCount: 542,
            friendsCount: 123,
            members: friends
          }
        })
      }
      // this.groups.push({
      //   wxid: Math.random().toString(16).slice(2),
      //   avatar: '',
      //   name: `群聊${i}`,
      //   memberCount: 542,
      //   friendsCount: 123,
      //   members: friends
      // })
    }
    // this.filteredGroups = this.groups;
    // this.progressList = [
    //   {
    //     service: {
    //       name: '客服一号'
    //     },
    //     time: '2019.6.12 11:35',
    //     type: 'active', // timing
    //     totalCount: 39,
    //     showDetail: false,
    //     listType: 'record',
    //     keyword: '优惠券',
    //     records: friends.slice(20),
    //     groups: this.groups
    //   },{
    //     service: {
    //       name: '客服一号'
    //     },
    //     time: '2019.6.12 11:35',
    //     type: 'instant', // timing
    //     totalCount: 39,
    //     keyword: '优惠券',
    //     showDetail: false,
    //     listType: 'record',
    //     records: friends.slice(30),
    //     groups: this.groups
    //   }
    // ]
    this.$nextTick(()=>{
      this.$element.render()
    })
  },
  computed: {
    filteredGroups(){
      // console.log(this.search)
      return this.groups.filter(group=>group.groupname.indexOf(this.search)>-1)
    },
    formatedAccounts() {
      if (!this.accounts.trim()) return []
      return this.accounts.split('\n');
    },
    isDiscuss() {
      console.log(this.$route)
      return this.$route.name == 'discuss'
    }
  },
  components: {
    ChooseServiceAccount,
    QuickReplies,
    Search,
    UserListItem,
    Group,
    Friend
  },
  methods: {
    getGroupList() {
      const service = this.service
      this.$api.group.list({
        csid: service.csid,
        wxaccount: service.wxid
      }).then(data=>{
        this.groups = data
       
        data.forEach(item=>{
          this.groupMap[item.groupno] = item
        })

      })
      .catch(e=>this.$msg(e))
    },

    getRecord(){
      const service = this.service
      this.$api.groupKeyword.get({
        csId: service.csid,
        wxAccount: service.wxid
      }).then(data=>{
        this.progressList = data.map(item=>{
          item.listType = 'record'
          return item
        })
        //this.groups = data
        console.log(data)
      })
      .catch(e=>this.$msg(e)) 
    },

    serviceChange(service) {
      this.service = service[0]
      this.getGroupList()
      this.getRecord()
    },
    searchChange(val) {
      this.search = val
      if (val == '') return this.filteredGroups = this.groups;
      this.filteredGroups = this.groups.filter(g=>g.name.indexOf(val)>-1);
    },
    changeGroupSelect(group) {
      if (this.checkedGroups.indexOf(group.groupno) > -1) {
        this.checkedGroups = this.checkedGroups.filter(id=>id!=group.groupno)
      } else {
        this.checkedGroups.push(group.groupno)
      }
    },
    toggleDetailShow(progress, index) {
      this.$set(this.progressList, index, {
        ...progress,
        showDetail: !progress.showDetail
      })
    },
    changeProgressListType(type, index) {
      const progress = this.progressList[index];
      this.$set(this.progressList, index, {
        ...progress,
        listType: type
      })
    },
    editSetting(res) {
      console.log('edit: ', res)
    },
    deleteSetting(res) {
      const service = this.service
      this.$api.groupKeyword.del({
        csId: service.csid,
        wxAccount: service.wxid,
        id:res.id
      }).then(data=>{
        this.progressList = this.progressList.filter(item=>item.id!=res.id)
        //this.groups = data
        console.log(data)
      })
      .catch(e=>this.$msg(e))   
    },
    deleteSettngGroup(progress,group) {
      const { id,groupnos } = progress;
      let groupnoArr = groupnos.split(',')
      groupnoArr = groupnoArr.filter(item=>item!=group)
      progress.groupnos = groupnoArr.join(',')
 
      this.$api.groupKeyword.update(progress)
        .then(data=>{
          this.progressList.map(_progress=>{
            if(id === _progress){
              return progress
            }
            return _progress
          })
        })
        .catch(console.log)
    },
    chooseMessage(message) {
      this.choosenMessage = message
    },
    confirmSend() {
      const keyword = this.keyword.trim()
      const groupnos = this.checkedGroups.join(',')

      if(!this.service)return this.$msg('请选择客服账号')
      if(!keyword)return this.$msg('请输入关键词')
      if(groupnos === '')return this.$msg('请选择群')
      const { csid,wxid } = this.service;
      const params = {
        keyword,
        csid,
        wxaccount:wxid,
        groupnos
      }

      this.$api.groupKeyword.insert(params)
        .then(data=>{
          data.listType = 'record'
          this.progressList.unshift(data)
          this.$msg('添加成功')
          console.log(data)
        })
        .catch(e=>this.$msg(e))
      console.log(this.checkedGroups)
    }
  }
}
</script>
<style scoped>
.discussDetailContainer .item{
  align-items: center
}
.discussDetailContainer .group-item{
  margin-left: 5px
}
.discussDetailContainer .groupList{
  display: grid;
  grid-template-columns: 33.333% 33.333% 33.333%;
  /* grid-template-rows: 33.333% 33.333% 33.333%; */
  grid-row-gap: 10px;
  /* grid-column-gap: 5px;  */
  height: 300px;
  overflow: auto;
  flex-shrink: 0
}
.progress-user{
  height: 250px;
  overflow:auto;
}
.progress-user-item{
  padding:5px 0
}
.progress-item-status{
  justify-content: space-around;
}
.set-group-item{
  padding: 5px 0;
  justify-content:space-between;
  align-items: center; 
}
.responseContainer .detailList  .set-group-del{
  margin-right: 100px
}
.progress-friend-item{
  width: 180px;
}
.progress-group-item{
  width:180px;
}
</style>
